var querySort = 'sort_visit';
var queryFilter = '';
var queryOrgId = window.location.hash.slice(1);
var selUserIds = [];
var selUserAndRole = [];
var pageSize = 10;
var pSize = 6;//群组
var count = 0;
var queryname="";
var c_sharesavedownload="";//分享保存下载权限
var c_people="";//人员权限
var c_invite="";//邀请权限
var c_posts="";//帖子权限
var queryCount = 0;
var windowflag = true;//用于滚动加载
$(function(){
	groupList();
	findOrgInfo();
	
	$(window).scroll(function(){
		var viewH =$(this).height();//可见高度
	    var contentH =$(document).height();//内容高度
	    var scrollTop =$(this).scrollTop();//滚动高度
	    if(scrollTop/(contentH -viewH)>=0.95){ //到达底部100px时,加载新内容
	      // 这里加载数据..
    	  if(windowflag&&pSize<queryCount){
    		  windowflag =false;
    		  pSize+=6;
    		  groupList();
		  }
	    }
	})
	$(".uploadBtn").click(function() {
		$("#file").click();
	});
	/**
	 * 排序
	 */
	/*$(".selSort").click(function(){
		$(".sortList").slideDown(1000);
	});
	$(".sortItem .sortIco").click(function(){
		$(".sortList").slideDown(1000);
	});*/
	$(".sortList .item").click(function(){
		var text = this.innerHTML;
		querySort = $(this).attr("value");
		$(".selSort")[0].innerHTML=text;
		/*$(".sortList").slideUp(1000);*/
		groupList();
	});
	/**
	 * 筛选
	 */
	/*$(".selFilter").click(function(){
		$(".filterList").slideDown(1000);
	});
	$(".sortItem .filterIco").click(function(){
		$(".filterList").slideDown(1000);
	});*/
	$(".filterList .item").click(function(){
		var text = this.innerHTML;
		queryFilter = $(this).attr("value");
		$(".selFilter")[0].innerHTML=text;
		/*$(".filterList").slideUp(1000);*/
		groupList();
	});
	/**
	 * 滚动条监听事件
	 */
	$(".userList").scroll(function() {
	  var divHeight = $(".userList").height();
	  var ulHeight = $(".userList ul").height();
	  if(divHeight+this.scrollTop>=ulHeight+10){
		  if(pageSize<count){
			  pageSize+=10;
			  selectUserList();
		  }
	  }
	});
	$("#groupInfoModal").find(".groupName").unbind("keyup");
	$("#groupInfoModal").find(".groupName").keyup(function(){
		$("#groupInfoModal").find(".error-msg").text("");
	});
	$("#orgId").val(queryOrgId);
	/**
	 * 打开第一步的模态框
	 * 模态框点击空白不消失
	 */
	$('.addDiv').click(function(){
		selUserIds = [];
		selUserAndRole=[];
		//初始化设置
		$("#groupConfModal").find(".itemName").each(function(){
			$(this).text("所有人");
		});
		$("#groupConfModal").find(".roleItem").each(function(){
			$(this).val(4);
		});
		if($("#groupInfoModal").find(".groupImg").find("img")[0]){
			$("#groupInfoModal").find(".groupImg").find("img").remove();
		}
		$("#groupName").val("");
		$("#groupDes").text("");
		$("#myModal").find(".selUser").each(function(){
			if($(this).find("#userImgSelf")[0])
				return;
			$(this).remove();
		});
		$.ajax({
			url:"../../../hivelearn/group/preAdd.json",
			success:function(data){
				$("#groupForm").find("[name='ORCHID_WEB_TOKEN']").val(data.tokenmessage.token);
			}
		});
		//自己信息
		$.ajax({
			url:"../../../portal/open/getCurrentUser.json",
			success:function(data){
				if(data.data.isLogin){
					var name = data.data.user.name;
					var photo = data.data.user.extendAccountInfo.headPhoto;
					$("#userNameSelf").text(data.data.user.name);
					if(photo){
						$("#userImgSelf").css("background","url('../../../components/gtattachment/open/downloadAttachment.json?attachmentId="+photo+"')");
					}else{
						$("#userImgSelf").css("background"," url('../../skin/img/default_head.png');background-size:40px;");
					}
					$("#userImgSelf").attr("title",name);
					$("#userNameSelf").attr("title",name);
					selectUserList();
					$('#myModal').modal({backdrop: 'static', keyboard: true});
				}
			}
		});
	});
	/**
	 * 打开第二步的模态框
	 */
	$('.fNext').click(function(){
		if(selUserIds.length==0){
			$("#groupInfoModal").find(".changeRole").hide();
		}else{
			$("#groupInfoModal").find(".changeRole").show();
		}
		$('#groupInfoModal').modal({backdrop: 'static', keyboard: true});
	});
	/**
	 * 打开设置组模态框
	 */
	$('.groupConf').click(function(){
		getGroupRole("");
		c_sharesavedownload = $("#groupConfModal").find("[name='sharesavedownload']").val();
		c_people = $("#groupConfModal").find("[name='people']").val();
		c_invite = $("#groupConfModal").find("[name='invite']").val();
		c_posts = $("#groupConfModal").find("[name='posts']").val();
		commmon_initRole();
		$('#groupConfModal').modal({backdrop: 'static', keyboard: true});
	});
	//更改成员角色
	$("#groupInfoModal").find(".changeRole").click(function(){
		if(selUserIds.length>0){
			$.ajax({
				url:"../../../learn/groupuser/findUserList.json",
				data:{"queryUserIds":selUserIds},
				traditional:true,
				success:function(data){
					for(var i = 0;i<data.data.resultList.length;i++){
						for(var j = 0;j<selUserAndRole.length;j++){
							var role = "人员";
							if(selUserAndRole[j].split(",")[1].indexOf("editor")!=-1){
								role = "人员";
							}else if(selUserAndRole[j].split(",")[1].indexOf("commenter")!=-1){
								role = "评论者";
							}else if(selUserAndRole[j].split(",")[1].indexOf("viewer")!=-1){
								role = "观看者";
							}else if(selUserAndRole[j].split(",")[1].indexOf("admin")!=-1){
								role = "管理者";
							}
							if(data.data.resultList[i].userId == selUserAndRole[j].split(",")[0]){
								data.data.resultList[i].roleName = role;
							}
						}
					}
					var dom = _.template($('#userRoleListTpl').html());
					dom = dom(data.data);
					$("#userRoleList").html(dom);
					//单个修改
					$("#userRoleList").find(".selStatus").each(function(){
						$(this).click(function(){
							var username = $(this).closest(".itemDiv").find(".userName").text();
							var selRole = "editor";
							var selUserId = $(this).closest(".itemDiv").find("[name='userId']").val();
							for(var i = 0;i<selUserAndRole.length;i++){
								if(selUserAndRole[i].split(",")[0]==selUserId){
									selRole = selUserAndRole[i].split(",")[1];
									break;
								}
							}
							$("#changeUserId").val(selUserId);
							$("#changeRoleModal").find(".changeUser").text(username);
							$("#changeRoleModal").find("[name='selectRole']").each(function(){
								if(selRole.indexOf($(this).val())!=-1){
									$(this).prop("checked",true);
								}
							});
							$("#changeRoleModal").modal({backdrop: 'static', keyboard: true});
							var sharesavedownloadVal = $("[name='sharesavedownload']").val();
							var peopleVal = $("[name='people']").val();
							var inviteVal = $("[name='invite']").val();
							var postsVal = $("[name='posts']").val();
							c_initRole(sharesavedownloadVal,peopleVal,inviteVal,postsVal);
						});
					})
					$("#groupRoleModal").modal({backdrop: 'static', keyboard: true});
				}
			});
		}
	})
	/**
	 * 下拉区域
	 */
/*	$(".js_sel_1").click(function(){
		$(".js_sel_1List").slideDown(1000);
	});
	$(".sortItem .js_sel_1Ico").click(function(){
		$(".js_sel_1List").slideDown(1000);
	});*/
	$(".js_sel_1List .item").click(function(){
		var text = this.innerHTML;
		var val = $(this).attr("value");
		$(this).closest(".rolePer").find(".roleItem").val(val);
		$(".js_sel_1")[0].innerHTML=text;
		commmon_initRole();
		/*$(".js_sel_1List").slideUp(1000);*/
	});
	
	/*$(".js_sel_2").click(function(){
		$(".js_sel_2List").slideDown(1000);
	});
	$(".sortItem .js_sel_2Ico").click(function(){
		$(".js_sel_2List").slideDown(1000);
	});*/
	$(".js_sel_2List .item").click(function(){
		var text = this.innerHTML;
		$(".js_sel_2")[0].innerHTML=text;
		var val = $(this).attr("value");
		$(this).closest(".rolePer").find(".roleItem").val(val);
		commmon_initRole();
		/*$(".js_sel_2List").slideUp(1000);*/
	});
	
	/*$(".js_sel_3").click(function(){
		$(".js_sel_3List").slideDown(1000);
	});
	$(".sortItem .js_sel_3Ico").click(function(){
		$(".js_sel_3List").slideDown(1000);
	});*/
	$(".js_sel_3List .item").click(function(){
		var text = this.innerHTML;
		$(".js_sel_3")[0].innerHTML=text;
		var val = $(this).attr("value");
		$(this).closest(".rolePer").find(".roleItem").val(val);
		commmon_initRole();
		/*$(".js_sel_3List").slideUp(1000);*/
	});
	
	/*$(".js_sel_4").click(function(){
		$(".js_sel_4List").slideDown(1000);
	});
	$(".sortItem .js_sel_4Ico").click(function(){
		$(".js_sel_4List").slideDown(1000);
	});*/
	$(".js_sel_4List .item").click(function(){
		var text = this.innerHTML;
		$(".js_sel_4")[0].innerHTML=text;
		var val = $(this).attr("value");
		$(this).closest(".rolePer").find(".roleItem").val(val);
		commmon_initRole();
		/*$(".js_sel_4List").slideUp(1000);*/
	});
	
	/*$(".js_sel_5").click(function(){
		$(".js_sel_5List").slideDown(1000);
	});
	$(".sortItem .js_sel_5Ico").click(function(){
		$(".js_sel_5List").slideDown(1000);
	});*/
	$(".js_sel_5List .item").click(function(){
		var text = this.innerHTML;
		$(".js_sel_5")[0].innerHTML=text;
		var val = $(this).attr("value");
		$(this).closest(".rolePer").find(".roleItem").val(val);
		/*$(".js_sel_5List").slideUp(1000);*/
	});
	
	/*$(".js_sel_6").click(function(){
		$(".js_sel_6List").slideDown(1000);
	});
	$(".sortItem .js_sel_6Ico").click(function(){
		$(".js_sel_6List").slideDown(1000);
	});*/
	$(".js_sel_6List .item").click(function(){
		var text = this.innerHTML;
		$(".js_sel_6")[0].innerHTML=text;
		var val = $(this).attr("value");
		$(this).closest(".rolePer").find(".roleItem").val(val);
		/*$(".js_sel_6List").slideUp(1000);*/
	});
	
	/*$(".js_sel_7").click(function(){
		$(".js_sel_7List").slideDown(1000);
	});
	$(".sortItem .js_sel_7Ico").click(function(){
		$(".js_sel_7List").slideDown(1000);
	});*/
	$(".js_sel_7List .item").click(function(){
		var text = this.innerHTML;
		$(".js_sel_7")[0].innerHTML=text;
		var val = $(this).attr("value");
		$(this).closest(".rolePer").find(".roleItem").val(val);
		/*$(".js_sel_7List").slideUp(1000);*/
	});
});
//列表查询
function groupList() {
	$.get('../../../hivelearn/group/findGroupList.json?querySort=' + querySort
			+ '&queryFilter=' + queryFilter+'&queryOrgId='+queryOrgId+"&pageSize="+pSize, function(datas) {
		if (datas.success) {
			queryCount=datas.data.count;
			$.each(datas.data.resultList, function (index, item) {
				var time = new Date(item.createDate);
				var year = time.getFullYear();
				var month = time.getMonth()+1;
				item.createDate = year + '年' + month+'月';
			});
			$(".js-heading-num").text(queryCount);
			var dom = _.template($('#groupTpl').html());
			dom = dom(datas.data);
			$("#group").html(dom);
			windowflag = true;
		}
	})
}
//机构查询
function findOrgInfo() {
	$.get('../../../opwguser/org/findOrgInfo.json?queryOrgId='+queryOrgId, function(data) {
		if (data.success) {
			$(".js-heading-dept").text(data.data.orgInfo.organizationName+"：");
			if(data.data.isGroupManager != 1){
				$(".addDiv").hide();
			}
		}
	})
}
//跳主题
function toTopic(id){
	$.ajax({
		url:'../../../hivelearn/group/findGroup.json?id=' + id,
		success:function(data){
			window.location.href="../meetingtheme/meetingTheme.html#"+id+","+queryOrgId;
		}
	})
	
}
function search() {
	querySort = $("#querySort").val();
	queryFilter = $("#queryFilter").val();
	groupList();
}
function preAdd() {
	$.get('../../../hivelearn/group/preAdd.json', function(data) {
		if (data.success) {
			var dom = _.template($('#addTpl').html());
			dom = dom(data);
			$("#add").html(dom);
		}
	})
}
function addGroup() {
	$.ajax({
		url : '../../../hivelearn/group/saveGroup.json',
		data : $('#groupForm').serialize(),
		type : "POST",
		success : function() {
			$("#add").empty();
			console.log("submit success");
		}
	});
}
//查询人员列表
function searchUserList(){
	queryname = $("#searchUserName").val()?$("#searchUserName").val():"";
	selectUserList();
}
//选中
function selUser(e){
	var userId = $(e).closest(".itemDiv").find("[name='userId']").val();
	var userImg = $(e).closest(".itemDiv").find(".userImg").prop("outerHTML");
	var userName = $(e).closest(".itemDiv").find(".userName").prop("outerHTML");
	selUserIds.push(userId);
	selUserAndRole.push(userId+",editor");//默认角色
	var ele = "<div class=\"selUser\">"
			  +"<input type=\"hidden\" name=\"userId\" value=\""+userId+"\"/>"
		      +userImg
		      +userName
		      +" 		<span class=\"delUser glyphicon glyphicon-remove\" onclick=\"delUser(this)\"></span>"
		      +"  	</div>"
	//计数
	$("#myModal").find(".selNum").text(selUserIds.length?"已选中"+selUserIds.length+"人":"");
	$(".selUserGroup").append(ele);
}
//移除
function delUser(e){
	var selUser = $(e).closest(".selUser");
	var userId = $(e).closest(".selUser").find("[name='userId']").val();
	$("#selectUserList").find("[name='userId']").each(function(){
		if($(this).val()==userId){
			$(this).closest(".userItem").find(".sel").click();
		}
	});
	selUser.remove();
	for(var i = 0;i<selUserIds.length;i++){
		if(selUserIds[i]==userId){
			selUserIds.splice(i,1);
			break;
		}
	}
}
//撤销选中
function unSelUser(e){
	var userId = $(e).closest(".userItem").find("[name='userId']").val();
	$(".selUserGroup").find("[name='userId']").each(function(){
		if($(this).val()==userId){
			$(this).closest(".selUser").remove();
		}
	});
	for(var i = 0;i<selUserIds.length;i++){
		if(selUserIds[i]==userId){
			selUserIds.splice(i,1);
			for(var j = 0;j<selUserAndRole.length;j++){
				if(selUserAndRole[j].split(",")[0]==userId){
					selUserAndRole.splice(j, 1);
					break;
				}
			}
			break;
		}
	}
	//计数
	$("#myModal").find(".selNum").text(selUserIds.length?"已选中"+selUserIds.length+"人":"");
}
//保存组
function saveGroup(){
	var groupName = $("#groupInfoModal").find(".groupName").val();
	var groupDes = $("#groupInfoModal").find(".groupDes").text();
	if(!groupName||!groupName.replace(/(^\s*)|(\s*$)/g,'')){
		$("#groupInfoModal").find(".error-msg").text("组名不能为空");
		return ;
	}
	$("#groupForm").find("[name='groupName']").val(groupName.replace(/(^\s*)|(\s*$)/g,''));
	$("#groupForm").find("[name='aboutGroup']").val(groupDes.replace(/(^\s*)|(\s*$)/g,''));
	for(var i=0;i<selUserAndRole.length;i++){
		var val = selUserAndRole[i].replace("#","");
		var ele = "<input type=\"hidden\" name=\"userAndRoles\" value=\""+val+"\" />";
		$("#groupForm").append(ele);
	}
	$("#userAndRoles").val(selUserAndRole);
	var userOpenType = null; 
	var obj = document.getElementsByName("userOpenType");
	for (var i = 0; i < obj.length; i++){ //遍历Radio 
		if(obj[i].checked){ 
			userOpenType = obj[i].value; 
		} 
	} 
	$.ajax({
		url:"../../../hivelearn/group/saveGroup.json?userOpenType="+userOpenType,
		data : $('#groupForm').serialize(),
		type : "POST",
		traditional:true,
		success:function(){
			$("#myModal").modal("hide");
			$("#groupInfoModal").modal("hide");
			groupList();
		}
	});
}
//初始化角色
function initRole(){
	/*$("#groupConfModal").find(".itemName").each(function(){
		$(this).text("所有人");
	});
	$("#groupConfModal").find(".roleItem").each(function(){
		$(this).val(4);
	})*/
	 $("#groupConfModal").find("[name='sharesavedownload']").val(c_sharesavedownload);
	 $("#groupConfModal").find("[name='people']").val(c_people);
	 $("#groupConfModal").find("[name='invite']").val(c_invite);
	 $("#groupConfModal").find("[name='posts']").val(c_posts);
	 $("#groupConfModal").find(".rolePer").each(function(){
			var val=$(this).find(".roleItem").val();
			if(val==4){
				$(this).find(".itemName").text("所有人");
			}else if(val==3){
				$(this).find(".itemName").text("编辑、管理员和自己");
			}else if(val==2){
				$(this).find(".itemName").text("管理员和自己");
			}else if(val==1){
				$(this).find(".itemName").text("仅自己");
			}
		});
}
function selectUserList(){
	$.ajax({
		url:"../../../learn/groupuser/findUserList.json",
		data:{"pageSize":pageSize,"queryUserName":queryname},
		success:function(data){
			data.data.selUsers = selUserIds.join(",");
			if(data.data.count){
				count = data.data.count;
			}else{
				count = 0;
			}
			var dom = _.template($('#selectUserListTpl').html());
			dom = dom(data.data);
			$("#selectUserList").html(dom);
			/**
			 * 选择取消点击事件
			 */
			$('.unSel').click(function(){
				selUser(this);
				$(this).fadeOut(300,function(){
					$(this).next().fadeIn(300);
				});
			});
			$('.sel').click(function(){
				$(this).fadeOut(300,function(){
					$(this).prev().fadeIn(300);
				});
			});
		}
	});
}
function toShareLearning(){
	window.location.href="../../../hivelearnweb/portal/shareLearning/shareLearning.html";
};
//修改默认角色
function changeDefaultRole(){
	var defalutRole = $("#groupConfModal").find("[name='defaultRole']:checked").val();
	for(var i=0;i<selUserAndRole.length;i++){
		if(selUserAndRole[i].indexOf("#")==-1){//强制修改的不根据默认角色改变
			if(defalutRole==2){
				selUserAndRole[i] = selUserAndRole[i].split(",")[0]+",commenter";
			}else if(defalutRole==1){
				selUserAndRole[i] = selUserAndRole[i].split(",")[0]+",editor";
			}
		}
	}
}
//保存单人修改角色
function changeOneUserRole(){
	var changeUserId = $("#changeUserId").val();
	var role = $("#changeRoleModal").find("[name='selectRole']:checked").val();
	for(var i =0;i<selUserAndRole.length;i++){
		if(selUserAndRole[i].split(",")[0]==changeUserId){
			selUserAndRole[i]=changeUserId+","+role+"#";
		}
	}
	$("#userRoleList").find(".userItem").each(function(){
		var userId = $(this).find("[name='userId']").val();
		if(userId==changeUserId){
			if(role=="editor"){
				$(this).find(".selStatus").text("人员");
			}else if(role=="commenter"){
				$(this).find(".selStatus").text("评论者");
			}else if(role=="viewer"){
				$(this).find(".selStatus").text("观看者");
			}else if(role=="admin"){
				$(this).find(".selStatus").text("管理者");
			}
		}
	});
}
/***********图片上传*************/
function uploadFile() {
	 $("#uploadForm").ajaxSubmit({
    	url: "../../../hivelearn/topic/uploadImage.json?_t="+new Date().getTime(),
        data:$("#uploadForm").serialize(),
        dataType:"json",
        success:function(data){
        	$("#groupInfoModal").find(".groupImg").find("img").remove();
			var img = "<img id=\"topicCover\" src=\"../../../components/gtattachment/open/downloadAttachment.json?attachmentId="
							+ data.attachid+"\"/>";
			$("#groupInfoModal").find(".groupImg").append(img);
			$('[name="groupCover"]').val(data.attachid);
			console.log("上传成功");
			$("#file").val("");
		},
		error:function(data){
			console.log("服务器异常");
			$("#file").val("");
		}
    });
	/*$.ajax({
		url : "../../../hivelearn/topic/uploadImage.json",
		data : new FormData($('#uploadForm')[0]),
		method : "post",
		processData : false,
		contentType : false,
		cache : false,
		success : function(data) // 服务器成功响应处理函数
		{
			$("#groupInfoModal").find(".groupImg").find("img").remove();
			var img = "<img id=\"topicCover\" src=\"../../../components/gtattachment/open/downloadAttachment.json?attachmentId="
							+ data.data.attachid+"\"/>";
			$("#groupInfoModal").find(".groupImg").append(img);
			$('[name="groupCover"]').val(data.data.attachid);
			console.log("上传成功");
			$("#file").val("");

		},
		error : function(data)// 服务器响应失败处理函数
		{
			console.log("服务器异常");
			$("#file").val("");
		}
	});*/
//	return false;
}
//检查
/*function checkfile(target) {
	if(!$(target).val()){
		return false;
	}
	var isIE = /msie/i.test(navigator.userAgent) && !window.opera; 
	var fileSize = 0;
	var filetypes = [ ".jpg", ".png", ".gif"];
	var filepath = target.value;
	var filemaxsize = 1024 * 2;// 2M
	if (filepath) {
		var isnext = false;
		var fileend = filepath.substring(filepath.indexOf("."));
		if (filetypes && filetypes.length > 0) {
			for ( var i = 0; i < filetypes.length; i++) {
				if (filetypes[i] == fileend) {
					isnext = true;
					break;
				}
			}
		}
		if (!isnext) {
			$("#msgModal").find(".msg").text("请选择.png，.jpg，.gif图片文件上传");
			$("#msgModal").modal("show");
			target.value = "";
			return false;
		}
	} else {
		return false;
	}
	if (isIE && !target.files) {
		var filePath = target.value;
		var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
		if (!fileSystem.FileExists(filePath)) {
			$("#msgModal").find(".msg").text("图片不存在，请重新输入！");
			$("#msgModal").modal("show");
			return false;
		}
		var file = fileSystem.GetFile(filePath);
		fileSize = file.Size;
		ieUpload(target,"uploadForm",uploadFile,filemaxsize);
	} else {
		fileSize = target.files[0].size;
		var size = fileSize / 1024;
		if (size > filemaxsize) {
			$("#msgModal").find(".msg").text("图片大小不能大于" + filemaxsize / 1024 + "M！");
			$("#msgModal").modal("show");
			target.value = "";
			return false;
		}
		if (size <= 0) {
			$("#msgModal").find(".msg").text("图片大小不能为0M！");
			$("#msgModal").modal("show");
			target.value = "";
			return false;
		}
		uploadFile();
	}
}*/
/***********图片上传*************/
